<?php
/**
 * Author: lee wei
 * Date: 2021/12/8
 */
namespace app\admin\service;

use app\common\model\Admin;
use app\common\exception\BusinessException;

class LoginService extends BaseService
{

    public function login($username, $password)
    {
        $admin_info = Admin::field('id,password,status')
            ->where('username',$username)
            ->find();

        if(empty($admin_info)){
            $this->setError('用户名或密码不正确');
            return false;
        }

        $md5Password = $this->userMd5($password);
        if($admin_info['password'] === $md5Password){
            $this->setError('用户名或密码不正确');
            return false;
        }

        if($admin_info['status'] == 0){
            $this->setError('用户已被禁止登录');
            return false;
        }

        //更新登录记录
        Admin::where('id',$admin_info['id'])
            ->update([
                'last_login_time' => time(),
                'last_login_ip' => time(),
                'login' => time(),
            ]);

        return $admin_info;
    }

    public static function userMd5(string $str, string $auth_key = ''): string {
        if (!$auth_key) {
            $auth_key = config('apiadmin.AUTH_KEY');
        }

        return '' === $str ? '' : md5(sha1($str) . $auth_key);
    }

    /**
     * 获取最后产生的错误
     * @return string
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * 设置错误
     * @param string $error 信息信息
     */
    public function setError(string $error)
    {
        $this->error = $error;
    }

}